package com.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.bean.PersonBean;
import com.dao.IUserDao;

public class UserDao extends SimpleJdbcDaoSupport implements IUserDao {
	
	//查询用户名和密码是否匹配
	public int queryLogin(String ename, String password){
		int ret = 0;
		String sql = "select count(*) from tb_user where ename = ? and password = ?";
		ret = getSimpleJdbcTemplate().queryForInt(sql, ename, password);
		return ret;
	}
	
	//获取登录人员信息
	public PersonBean getUserInfo(String ename){
		final PersonBean bean = new PersonBean();
		String sql = "select * from tb_user where ename = ?";
		Object[] args = new Object[]{ename};
		getJdbcTemplate().query(sql, args, new RowCallbackHandler(){
			public void processRow(ResultSet rs) throws SQLException {
				bean.setId(rs.getInt("id"));
				bean.setEname(rs.getString("ename"));
				bean.setCname(rs.getString("cname"));
				bean.setRole(rs.getString("role"));
				bean.setPassword(rs.getString("password"));
			}
		});
		return bean;
	}
	
	//更新登录用户最后登录时间
	public int updateLogin(String ename){
		int ret = 0;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = format.format(new Date());
		String sql = "update tb_user set last_visit=? where ename=?";
		ret = getSimpleJdbcTemplate().update(sql, date, ename);
		return ret;
	}
	
	//查询用户密码
	public String queryPassword(String ename){
		String ret = null;
		String sql = "select password from tb_user where ename=?";
		ret = getSimpleJdbcTemplate().queryForObject(sql, new ParameterizedRowMapper<String>(){
			public String mapRow(ResultSet rs, int arg1) throws SQLException {
				return rs.getString("password");
			}
		}, ename);
		return ret;
	}
	
	//用户修改密码
	public int updatePassword(String ename, String newPassword){
		int ret = 0;
		String sql = "update tb_user set password=? where ename=?";
		ret = getSimpleJdbcTemplate().update(sql, newPassword, ename);
		return ret;
	}
	
	
}
